package cn.jsu.oj.dispatchServer.satellite.handler;

import cn.jsu.oj.dispatchServer.satellite.annotation.HandlerType;
import cn.jsu.oj.dispatchServer.satellite.config.ResourceConfig;
import cn.jsu.oj.dispatchServer.satellite.factory.Factory;
import cn.jsu.oj.dispatchServer.satellite.pojo.net.PackNet;
import cn.jsu.oj.dispatchServer.satellite.pojo.net.RequestNet;
import cn.jsu.oj.dispatchServer.satellite.pojo.net.ResponseNet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 重启处理器
 *
 * @author shan
 * @date 2022/07/05
 */
@Slf4j
@Component("restartHandler")
@HandlerType(typeNo = 7)
public class RestartHandler implements Handler {

    @Autowired
    Factory handlerFactory;

    private static final String JAR_NAME = ResourceConfig.getConfigString("client-info-jar-name");

    private static final String JAR_PATH = ResourceConfig.getConfigString("client-info-jar-path");

    @Override
    public void handle(PackNet<?> packNet) throws FileNotFoundException {
        String uuid = ((RequestNet) packNet.getMessage()).getUuid();
        ((Handler) handlerFactory.getProduct((short) 4))
                .handle(new PackNet<>(packNet.getChannel()
                        , new ResponseNet(uuid, true, (short) 7)));
        log.debug("----------项目即将重启，" + "指令号: " + uuid + "......");
        try {
            Runtime.getRuntime().exec("project " + JAR_NAME + " " + JAR_PATH + " restart");
        } catch (IOException e) {
            e.printStackTrace();
            try {
                Runtime.getRuntime().exec("systemctl restart tomcat");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}
